<template>
  <div id="spreadRoot" v-if="isShow" class="c-w100 c-h100vh">
    <div class="masker" @click="close"></div>
    <div class="c-flex-row c-flex-center c-pf c-pz101 c-p-tp50 c-p-lp50 c-w80 c-translate-xy-50 c-br8">
      <img id="spreadImg" class="c-w100 c-br8" alt/>
    </div>
    <div class="canvasBox c-maxWidth-none c-contextX-scroll">
      <div id="canvas" class="canvasStyle">
        <div class="c-p">
          <img :src="bgImg" id="bgImg" v-if="bgImg" class="c-maxWidth-none" style="width:375px;height:667px;"/>
          <div v-for="(item, index) in customizeControl" :key="index" :id="index" class="c-pa c-table" :style="{ width: item.width + 'px', height: item.height + 'px', color: item.color, fontSize: item.size + 'px', fontStyle: item.fontStyle, fontWeight: item.fontWeight == 'bold' ? item.fontWeight : Number(item.fontWeight), letterSpacing: (item.letterSpacing > 10 ? (item.letterSpacing - 1) : item.letterSpacing) + 'px', textAlign: item.textAlign, top: item.posY + 'px', left: item.posX + 'px', zIndex: 100 + Number(index), lineHeight: item.lineHeight + 'px' }">
            <img :src="qrImg" v-if="Number(item.type) == 1 && qrImg" :style="{width: item.width + 'px', height: item.height + 'px'}"/>
            <span class="c-tableCell" :style="{verticalAlign: item.verticalAlign}" v-if="Number(item.type) == 2">{{item.name}}</span>
            <div :style="{width: item.width + 'px', height: item.height + 'px'}" class="c-flex-column c-aligni-center" v-if="Number(item.type) == 3 && (headUrl || nickname)">
              <img class="c-brp50" :src="headUrl" :style="{width: '54px', height: '54px'}"/>
              <div v-if="nickname" class="c-mt10" :style="{verticalAlign: item.verticalAlign}">{{nickname}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
let html2canvas = null;
export default {
  name: "CustomCertificate",
  components: {},
  props: {
    customizeControl: { // 自定义控件
      type: Array,
      default: () => []
    },
    customizeImage: { // 自定义背景图
      type: String,
      default: ''
    },
    headimgurl: { // 用户头像
      type: String,
      default: ''
    },
    nickname: { // 用户昵称
      type: String,
      default: ''
    },
    qrcodeUrl: { // 自定义二维码
      type: String,
      default: ''
    },
    isShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      bgImg: "",
      qrImg: "",
      imgUrl: '',
      headUrl: ''
    };
  },
  created() {},
  mounted() {
  },
  computed: {},
  watch: {
    isShow(val) {
      if (val) {
        this.$nextTick(() => {
          //如果是ios,则去掉minHeight设置，防止底部前进后退导航挡住页面
          if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) && document.getElementById("spreadRoot")) {
            document.getElementById("spreadRoot").style.minHeight = "";
            // document.getElementById("spreadRoot").style.height = "100%";
          }
          document.querySelector("#spreadImg").setAttribute("src", "");
          setTimeout(() => {
            this.getInfo();
          }, 500);
        })
      }
    }
  },
  methods: {
    close() {
      this.$emit('closeCertificate')
    },
    getInfo() {
      import("@/utils/html2canvas.js").then(
        (sres) => {
          html2canvas = sres.default;
          this.bgImg = this.customizeImage;
          this.headUrl = this.headimgurl;
          this.qrImg = this.qrcodeUrl;
          //把微信二维码图片给转成base64,因为有些手机自动加上时间戳下载不下来比如vivo
          if (this.headimgurl) {
            let that = this
            let image = new Image()
            image.src = this.headimgurl // 处理缓存
            image.crossOrigin = 'anonymous' // 支持跨域图片
            image.onload = function () {
              try {
                let canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                let ctx = canvas.getContext('2d')
                ctx.drawImage(image, 0, 0, image.width, image.height)
                let dataURL = canvas.toDataURL('image/png')
                that.headUrl = dataURL;
                setTimeout(() => {
                  that.canvas();
                }, 800);
              } catch (error) {
                console.log("图片转成base64出错啦", error);
                that.headUrl = that.headimgurl;
                setTimeout(() => {
                  that.canvas();
                }, 800);
              }
            }
            image.error = function (e) {
              that.headUrl = that.headimgurl;
              setTimeout(() => {
                that.canvas();
              }, 800);
            }
          }
          if (this.qrcodeUrl) {
            let that = this
            let image = new Image()
            // if (this.qrcodeUrl.includes('https')) {
            //   this.qrcodeUrl = this.qrcodeUrl.replace('https', 'http')
            // }
            image.src = this.qrcodeUrl // 处理缓存
            image.crossOrigin = 'anonymous' // 支持跨域图片
            image.onload = function () {
              try {
                let canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                let ctx = canvas.getContext('2d')
                ctx.drawImage(image, 0, 0, image.width, image.height)
                let dataURL = canvas.toDataURL('image/png')
                that.qrImg = dataURL;
                setTimeout(() => {
                  that.canvas();
                }, 800);
              } catch (error) {
                console.log("图片转成base64出错啦", error);
                that.qrImg = that.qrcodeUrl;
                setTimeout(() => {
                  that.canvas();
                }, 800);
              }
            }
            image.error = function (e) {
              that.qrImg = that.qrcodeUrl;
              setTimeout(() => {
                that.canvas();
              }, 800);
            }
          }
          //转成base64结束
          this.$loading.show({
            text: "生成中...",
          });
        }
      );
    },
    canvas() {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
      let domTest = document.getElementById("canvas")
        ? document.getElementById("canvas")
        : null;
      let bgImg = document.getElementById("bgImg")
        ? document.getElementById("bgImg")
        : null;
      if (!domTest) {
        return;
      }
      html2canvas(domTest, {
        useCORS: true,
        height: bgImg ? bgImg.offsetHeight : 750, // 解决当前页面生成图片出现白边问题
        width: bgImg ? bgImg.offsetWidth : 1334,
      }).then((canvas) => {
        let ctx = canvas.getContext("2d");
        this.$nextTick(function() {
          this.canvasToImage(ctx);
        });
      });
    },
    canvasToImage(ctx) {
      try {
        let dataURL = ctx.canvas.toDataURL(
          "image/png?x-oss-process=style/common"
        );
        document.ontouchstart = true;
        document.ontuchmove = true;
        document.ontouchend = true;
        document.getElementById("spreadImg") && document.getElementById("spreadImg").setAttribute("src", dataURL);
        setTimeout(() => {
          this.$loading.hide();
        }, 500);
      } catch (err) {
        console.log(err);
      }
    },
  },
  beforeDestroy() {
  },
  destroyed() {},
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
#spreadRoot {
  min-height: auto;
  // height: 100%;
  overflow: hidden;
}
#spreadImg {
  margin: 0 auto;
}
.info {
  position: fixed;
  bottom: 0;
  box-shadow: 0px 0px 3px 0px rgba(0, 0, 0, 0.05);
}
.canvasBox {
  top: -999999999px;
  left: -30000000px;
  z-index: -999;
  position: absolute;
}
.canvasStyle {
  position: relative;
}
.c-maxWidth-none {
  max-width: none !important;
}
.masker {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
}
</style>
